# -*- coding: utf-8 -*-
from aip import AipOcr
import time
import urllib.request
import os.path 

""" 你的 APPID AK SK """
APP_ID = '10897480'
API_KEY = 'KTdyKjgGjL2OlFY1gSTSO5rl'
SECRET_KEY = '69FHS1qjtVKR796oU0pIRsoprvyV0IVP'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
options = {}
options["result_type"] = "excel"

""" 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()
    
def get_requestId(image):
    a = client.tableRecognitionAsync(image);
    requestId = a['result'][0]['request_id']
    print(requestId)
    return requestId


def get_result(requestId,file):
    b = client.getTableRecognitionResult(requestId,options)
    
    while (b['result']['ret_code'] != 3):
        time.sleep(5)
        b = client.getTableRecognitionResult(requestId,options)
    url = b['result']['result_data']
    print(b['result']['result_data'])
    urllib.request.urlretrieve (url, file+'.xls')
    
def scan_file(path,file):
    filePath = os.path.join(path,file)
    image = get_file_content(filePath)
    id = get_requestId(image)
    get_result(id,file)


def scan_dir(path):
    for file in os.listdir(path):
        if(file.endswith('.jpg')):
            scan_file(os.path.join(path),file)
    
    
scan_dir('b:/')
